package mo.leetcode_top;

import java.util.LinkedList;

class MovingAverage {

    private LinkedList<Integer> queue = new LinkedList<>();
    private double sum = 0;
    private int size;

    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.size = size;
    }

    public double next(int val) {
        while (queue.size() == size) {
            sum -= queue.removeFirst();
        }
        sum += val;
        queue.add(val);
        return  sum / queue.size();
    }

    public double next2(int val) {
        int left = 0;
        while ( queue.size() == size) {
            left = queue.removeFirst();
        }
        sum += val;
        queue.add(val);
        return  (sum - left) / queue.size();        //这一步有错误，left的减少没有同步到sum中
    }


    //["MovingAverage","next","next","next","next","next","next","next","next","next","next"]
    //[[5],[12009],[1965],[-940],[-8516],[-16446],[7870],[25545],[-21028],[18430],[-23464]]

    public static void main(String[] args) {
        MovingAverage movingAverage = new MovingAverage(5);
        MovingAverage movingAverage2 = new MovingAverage(5);

        System.out.print(movingAverage.next(12009)+"、");
        System.out.print(movingAverage2.next2(12009)+"、");
        System.out.println();

        System.out.print(movingAverage.next(1965)+"、");
        System.out.print(movingAverage2.next2(1965)+"、");
        System.out.println();

        System.out.print(movingAverage.next(-940)+"、");
        System.out.print(movingAverage2.next2(-940)+"、");
        System.out.println();

        System.out.print(movingAverage.next(-8516)+"、");
        System.out.print(movingAverage2.next2(-8516)+"、");
        System.out.println();

        System.out.print(movingAverage.next(-16446)+"、");
        System.out.print(movingAverage2.next2(-16446)+"、");
        System.out.println();

        System.out.print(movingAverage.next(7870)+"、");
        System.out.print(movingAverage2.next2(7870)+"、");
        System.out.println();

        System.out.print(movingAverage.next(25545)+"、");
        System.out.print(movingAverage2.next2(25545)+"、");
        System.out.println();

        System.out.print(movingAverage.next(-21028)+"、");
        System.out.print(movingAverage2.next2(-21028)+"、");
        System.out.println();

        System.out.print(movingAverage.next(18430)+"、");
        System.out.print(movingAverage2.next2(18430)+"、");
        System.out.println();

        System.out.print(movingAverage.next(-23464)+"、");
        System.out.print(movingAverage2.next2(-23464)+"、");
        System.out.println();




    }
}
